package com.ych.DemoSSM.common.web.controller;

import com.ych.DemoSSM.common.util.SystemUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("uploads")
@Api(tags = {"文件上传"})
public class FileUploadsController {

    @Value("${upload_root_path}")
    private String uploadRootPath;
    private String jpgUpload = "/static/";

    /**
     * 图片上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"jpgUpload.do"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ApiOperation(value = "图片上传")
    @ResponseBody
    public Map<String, Object> jpgUpload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Collection<MultipartFile> files = fileMap.values();

        List<Map<String, String>> data = new ArrayList();
        for (MultipartFile file : files) {
            StringBuffer fileName = new StringBuffer();
            fileName.append(this.jpgUpload);
            fileName.append(System.currentTimeMillis());
            fileName.append(getExtName(file.getOriginalFilename()));

            Map<String, String> retMap = new HashMap();
            retMap.put("name", file.getName());
            retMap.put("oriFileName", file.getOriginalFilename());
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(this.uploadRootPath + fileName.toString()));
                retMap.put("success", "0");
                retMap.put("uploadPath", fileName.toString());
            } catch (Exception e) {
                e.printStackTrace();
                retMap.put("success", "1");
            }
            data.add(retMap);
        }
        return SystemUtils.getSuccessMap(data);
    }

    private String getCurrentDate() {
        Date today = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

        return formatter.format(today);
    }

    private String getExtName(String fileName) {
        int i = fileName.lastIndexOf(".");
        return StringUtils.substring(fileName, i);
    }
}
